<template>
  <div class="basicForm">
    <editForm :formConfig="basicConfig" ref="basicForm" :formData="formData">
      <template #planCode="{ editFormInfo }">
        <el-input
          v-model="editFormInfo.planCode"
          size="mini"
          class="input-with-select input-link"
          readonly
          :disabled="true"
          placeholder="请选择工单"
          @click.native="showPlanPackage(editFormInfo)"
        ></el-input>
      </template>
    </editForm>
    <div class="attachConten">
      <div class="attachTitle">附件:</div>
      <div class="tebleDiv">
        <attachFormNew
          style="width: 60%"
          :disabled="baseAttachBtn"
          :attachSetting="attachSetting"
          isDelete
          multiple
          ref="attachForm"
        ></attachFormNew>
      </div>
    </div>
  </div>
</template>
<script>
/* 正常维护 */
import {
  getDetailsApi, //获取正常维护工单详情
} from "@/api/orderManagement/normalMaintenance";
/* 试验工单 */
import {
  getDetailsApi as getExperimentDetailsApi, //获取详情
} from "@/api/orderManagement/experimentOrder";
/* 计划检修 */
import {
  getDetailsApi as getRepairDetailsApi, //获取详情
} from "@/api/orderManagement/planRepair";
import {
  getDetailsApi as overhaulDetails, //获取大修工单详情
} from "@/api/orderManagement/overhaul";
export default {
  props: {
    initData: {
      type: Object,
      default: () => {
        return {};
      },
    },
    orderStatus: {
      type: String,
      default: "",
    },
    pageType: {
      type: String,
      default: "",
    },
    menuType: {
      type: String,
      default: "",
    },
    oldMajor: {
      type: String,
      default: null,
    },
  },
  components: {},
  data() {
    return {
      userInfo: this.$store.getters.userInfo,
      needStatus: null,
      status: "",
      currentContext: "",
      deptManageName: "",
      orderEquipPoList: [],
      workplace: [], //工作地点
      formData: {},
      basicConfig: {
        itemArr: [
          {
            label: "设备管理单位",
            prop: "deptManageName", //多选时，字段要为数组类型
            propArr: "deptManageArr",
            idsStr: "deptManage",
            multiple: false, //是否多选
            isOutOrg: 0, //是否是外单位
            option: [], //this.deptOption1
            allowCreate: true, //是否允许创建条目
            type: "dept-select", //类型
            trigger: "change",
            methods: (obj) => {
              this.currentDept = obj[0];
              this.deptManage = obj[0].id;
              this.deptManageName = obj[0].name;
              let arr = [];
              arr.push(obj[0].id);
              setTimeout(() => {
                this.$refs.basicForm.setItemConfig(
                  "deviceName",
                  arr,
                  "managerUnit"
                );
              }, 400);
            },
            required: true,
            span: 6,
          },
          {
            type: "select",
            label: "专业",
            prop: "major",
            required: true,
            selectOption: this.$store.getters["dirtData"]("common_major"),
            formatter: (val) => {
              return this.$store.getters["fineDirtDataName"](
                "common_major",
                val
              );
            },
            span: 6,
          },
          // {
          //   label: "工作地点",
          //   prop: "locationName",
          //   idsStr: "location",
          //   type: "location",
          //   trigger: "change",
          //   required: true,
          //   methods: obj => {},
          //   span: 6
          // },

          {
            label: "工作地点",
            prop: "locationName", //多选时，字段要为数组类型
            propArr: "locationArr",
            idsStr: "location",
            orgStr: "locationType", //
            multiple: true, //是否多选
            option: [], //this.deptOption1
            allowCreate: true, //是否允许创建条目
            type: "location-select", //类型
            trigger: "change",
            methods: (obj) => {
              this.workplace = [];
              obj.map((i) => {
                let place = {
                  location: i.isOutOrg == "-1" ? "" : i.value,
                  locationName: i.label,
                  orderId: this.formData.id,
                  orderType: "defect",
                };
                this.workplace.push(place);
              });
            },
            required: true,
            rows: 2,
            span: 6,
          },

          {
            type: "select",
            label: "工单性质",
            prop: "nature",
            required: true,
            selectOption: [
              {
                name: "生产类",
                label: "生产类",
                value: "1",
              },
              {
                name: "非生产类",
                label: "非生产类",
                value: "0",
              },
            ],
            span: 6,
          },
          {
            label: "计划起止时间",
            prop: "dispatchTime",
            type: "datetimerange",
            required: true,
            pickerOptions: {
              disabledDate(time) {
                return time.getTime() < Date.now() - 3600 * 1000 * 24;
              },
            },
            methods: (obj) => {
              let startTime = new Date(obj[0]);
              let endTime = new Date(obj[1]);
              let timeLimit = (endTime - startTime) / 1000 / 60 / 60 / 24;
              this.$refs.basicForm.setFormItem(
                "timeLimit",
                timeLimit.toFixed(2)
              );
            },
            span: 6,
          },
          {
            label: "工期(天)",
            prop: "timeLimit",
            type: "text",
            placeholder: "选完起止时间后自动计算",
            required: true,
            disabled: true,
            span: 6,
          },
          {
            type: "select",
            label: "是否需要作业表单",
            prop: "needStatus",
            required: true,
            selectOption: [
              {
                name: "是",
                label: "是",
                value: 1,
              },
              {
                name: "否",
                label: "否",
                value: 0,
              },
            ],
            methods: (obj) => {
              this.needStatus = obj.value;
            },
            span: 6,
          },
          {
            type: "select",
            label: "工单来源",
            prop: "sourceId",
            selectOption: this.$store.getters["dirtData"]("order_source"),
            formatter: (val) => {
              return this.$store.getters["fineDirtDataName"](
                "order_source",
                val
              );
            },
            methods: (obj) => {},
            disabled: true,
            span: 6,
          },
          {
            label: "计划编号",
            prop: "planCode",
            type: "text",
            isHide: true,
            disabled: false,
            min: 0,
            span: 6,
          },
          {
            label: "设备",
            prop: "deviceName", //多选时，字段要为数组类型
            propArr: "deviceArr",
            idsStr: "deviceId",
            filterConfig: ["filterManagerUnit"],
            //过滤条件：hasManagerUnit:该设备是否关联单位，filterManagerUnit:筛选指定单位的设备,filterStandard:关联了标准的设备
            managerUnit: [], //指定过滤的设备管理单位id filterConfig包含filterManagerUnit的时候使用
            // standardType: "maintain",
            //标准类型 正常维护：maintain,大修：overhaul,检修：repair,试验：experiment，巡视：patrol
            multiple: true, //是否多选
            allowCreate: false, //是否允许创建条目
            option: [], //this.deptOption
            type: "device-select", //类型
            trigger: "change",
            required: true,
            methods: (obj) => {
              this.orderEquipPoList = [];
              obj.map((i) => {
                let obj = {
                  equipmentId: i.id || i.value,
                  equipmentName: i.name || i.label,
                  orderId: this.formData.id || "",
                  orderType: "maintain",
                };
                this.orderEquipPoList.push(obj);
              });
            },
            isHide: true,
            rows: 3,
            span: 12,
          },
          {
            label: "工作内容",
            prop: "context",
            type: "textarea",
            maxlength: "100",
            required: true,
            span: 12,
            rows: 3,
            methods: (val) => {
              this.currentContext = val;
            },
          },
          {
            label: "备注",
            prop: "marks",
            type: "textarea",
            maxlength: "100",
            span: 12,
            rows: 3,
          },
        ],
      },
      //附件设置
      attachSetting: {
        businessId: "", //单据的ID
        businessType: "base",
      },
      deptManage: "",
    };
  },
  computed: {
    baseAttachBtn() {
      if (
        ["DRAFT", undefined, ""].includes(this.status) &&
        ["edit", "add"].includes(this.pageType)
      ) {
        return false;
      } else {
        return true;
      }
    },
    defaultTitle() {
      let deptManageName = this.deptManageName || "";
      let currentContext = this.currentContext || "";
      return deptManageName + currentContext;
    },
  },
  watch: {
    defaultTitle: {
      handler(val) {
        this.orderTitle = val;
        this.$emit("setOrderTitle", val);
      },
    },
    orderStatus: {
      handler(val) {
        this.status = val;
      },
    },
    needStatus: {
      handler(val) {
        this.changeFormItem(val);
        if (!val) {
          this.orderEquipPoList = [];
          this.$refs.basicForm.setFormItem("deviceName", "");
          this.$refs.basicForm.setFormItem("deviceArr", "");
          this.$refs.basicForm.setFormItem("deviceId", "");
        }
        this.$emit("setNeedStatus", val);
      },
    },
    pageType: {
      handler(val) {
        if (val != "add") {
          this.initForm();
        } else {
          this.init();
        }
      },
    },
    deptManage: {
      handler(val) {
        this.$emit("setDeptIds", [val]);
      },
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.formData = this.initData;
      this.status = this.orderStatus;
      if (["add", "orderAdd", ""].includes(this.pageType)) {
        //新增
        if (this.pageType == "orderAdd") {
          this.getOverhaulDetails();
        } else {
          this.formData.needStatus = 1;
          this.formData.sourceId = "enter_order";
          /* 设备管理单位 */
          let { orgName, orgId, isOutOrg } = this.userInfo;
          let option = this.$utils.getOptionData(
            orgName,
            orgId,
            isOutOrg || "0"
          );
          if (this.$refs.basicForm) {
            this.$refs.basicForm.setItemOption("deptManageName", option);
          }
          this.formData.deptManageName = orgName;
          this.formData.deptManage = orgId;
          this.formData.deptManageArr = orgId;
          this.deptManageName = orgName;
          this.deptManage = orgId;
        }
      }
    },
    initForm() {
      let itemArr = [];
      $.extend(true, itemArr, this.basicConfig.itemArr);
      itemArr.map((i) => {
        if (
          this.status != "DRAFT" ||
          ["query", "detail"].includes(this.pageType)
        ) {
          i.disabled = true;
        } else {
          if (!["timeLimit", "sourceId"].includes(i.prop)) {
            i.disabled = false;
          }
        }
        if (i.prop == "deviceName") {
          i.managerUnit = [this.deptManage];
        }
      });

      this.basicConfig.itemArr = itemArr;
    },
    getOrderDetails(id) {
      let dataId = id;
      getDetailsApi(dataId).then((res) => {
        let data = res.data;
        if (this.oldMajor) {
          data.major = this.oldMajor;
        }
        data.status = "";
        delete data.id;
        delete data.createByName;
        delete data.createBy;
        delete data.deptId;
        delete data.deptName;
        delete data.planCode;
        data.sourceId = "enter_order";
        this.deptManage = data.deptManage;
        this.deptManageName = data.deptManageName;
        this.currentContext = data.context;
        this.orderTitle = data.title;
        if (data.planCode) {
          this.basicConfig.itemArr[8].isHide = false;
        }
        //给标题赋值
        this.$emit("setOrderTitle", this.orderTitle);
        if (
          data.title == data.deptManageName + data.context ||
          [null, ""].includes(data.title)
        ) {
          if ([null, ""].includes(data.title)) {
            this.$message.warning("检测到工单标题为空，已为您自动生成标题！");
            this.orderTitle = data.deptManageName + data.context;
            this.$emit("setOrderTitle", this.orderTitle);
          }
          //用户是否自定义了工单名
          this.$emit("initUserInput", false);
        } else {
          this.$emit("initUserInput", true);
        }
        /* 工期 */
        data.timeLimit = this.$utils.getTimeDiffe(
          new Date(data.startTime),
          new Date(data.endTime)
        );
        //是否需要作业表单
        this.needStatus = data.needStatus;
        this.workplace = data.orderLocationList;
        /* 初始化设备管理单位 */
        if (data.startTime) {
          data.dispatchTime = [data.startTime, data.endTime];
        }
        data.maintainReadyPoList.forEach((item) => {
          delete item.id;
          delete item.maintainId;
        });
        data.maintainEquipmentPoList.forEach((item) => {
          delete item.id;
          delete item.maintainId;
        });
        data.orderEquipPoList.forEach((item) => {
          delete item.id;
          delete item.orderId;
        });
        data.orderLocationList.forEach((item) => {
          delete item.id;
          delete item.orderId;
        });
        this.$emit("changeFormData", data);
        setTimeout(() => {
          let deviceOption = [];
          let device = [],
            deviceName = []; /* 只能选当前设备管理单位下的设备 */
          if (this.needStatus == 0) {
            this.orderEquipPoList = data.orderEquipPoList || [];
            /* 初始化设备 */
            this.orderEquipPoList.map((i) => {
              if (i) {
                device.push(i.equipmentId);
                deviceName.push(i.equipmentName);
              }
            });
            deviceOption = this.$utils.getOptionData(
              deviceName.toString(),
              device.toString()
            );
          }
          let { deptManageName, deptManage } = data;
          let option = this.$utils.getOptionData(
            deptManageName,
            deptManage,
            "0"
          );
          let workplace = data.orderLocationList; //工作地点
          let placeName = [],
            placeId = [],
            placeType = [];
          workplace.map((i) => {
            placeName.push(i.locationName);
            if (i.location) {
              placeId.push(i.location);
              placeType.push("0");
            } else {
              //临时单位
              placeId.push(i.locationName);
              placeType.push("-1");
            }
          });
          data.locationName = placeName.toString();
          data.locationArr = placeId;
          data.location = placeId.toString();
          data.locationType = placeType.toString();
          let workplaceOption = this.$utils.getOptionData(
            placeName.toString(),
            placeId.toString(),
            placeType.toString()
          );
          if (this.$refs.basicForm) {
            this.$refs.basicForm.setItemOption("deviceName", deviceOption); //设备
            this.$refs.basicForm.setItemOption("deptManageName", option);
            this.$refs.basicForm.setItemOption("locationName", workplaceOption);
          }
          /* 给设备输入框赋值 */
          data.deviceName = deviceName.toString();
          data.deviceId = device.toString();
          data.deviceArr = device;
          /* 给设备管理单位框赋值 */
          data.deptManageArr = deptManage;
          this.formData = data;
        }, 100);
      });
    },
    //获取工单基本信息
    getDetails(id) {
      let dataId = id ? id : this.formData.id;
      var actionApi = null;
      if (this.menuType == "maintain") {
        /* 正常维护单 */
        actionApi = getDetailsApi;
      } else if (this.menuType == "experiment") {
        /* 试验工单 */
        actionApi = getExperimentDetailsApi;
      } else if (this.menuType == "repair") {
        /* 计划检修 */
        actionApi = getRepairDetailsApi;
      }
      actionApi(dataId).then((res) => {
        let data = res.data;
        if (this.oldMajor) {
          data.major = this.oldMajor;
        }
        this.status = data.status;
        this.deptManage = data.deptManage;
        this.initForm();
        this.deptManageName = data.deptManageName;
        this.currentContext = data.context;
        this.orderTitle = data.title;
        if (data.planCode) {
          this.basicConfig.itemArr[8].isHide = false;
        }
        //给标题赋值
        this.$emit("setOrderTitle", this.orderTitle);
        if (
          data.title == data.deptManageName + data.context ||
          [null, ""].includes(data.title)
        ) {
          if ([null, ""].includes(data.title)) {
            this.$message.warning("检测到工单标题为空，已为您自动生成标题！");
            this.orderTitle = data.deptManageName + data.context;
            this.$emit("setOrderTitle", this.orderTitle);
          }
          //用户是否自定义了工单名
          this.$emit("initUserInput", false);
        } else {
          this.$emit("initUserInput", true);
        }
        /* 工期 */
        data.timeLimit = this.$utils.getTimeDiffe(
          new Date(data.startTime),
          new Date(data.endTime)
        );
        this.status = data.status;
        //初始化附件ID
        this.attachSetting.businessId = data.id;
        //是否需要作业表单
        this.needStatus = data.needStatus;
        this.workplace = data.orderLocationList;
        /* 初始化设备管理单位 */
        if (data.startTime) {
          data.dispatchTime = [data.startTime, data.endTime];
        }
        this.$emit("changeFormData", data);
        setTimeout(() => {
          let deviceOption = [];
          let device = [],
            deviceName = []; /* 只能选当前设备管理单位下的设备 */
          if (this.needStatus == 0) {
            this.orderEquipPoList = data.orderEquipPoList || [];
            /* 初始化设备 */
            this.orderEquipPoList.map((i) => {
              if (i) {
                device.push(i.equipmentId);
                deviceName.push(i.equipmentName);
              }
            });
            deviceOption = this.$utils.getOptionData(
              deviceName.toString(),
              device.toString()
            );
          }
          let { deptManageName, deptManage } = data;
          let option = this.$utils.getOptionData(
            deptManageName,
            deptManage,
            "0"
          );
          let workplace = data.orderLocationList; //工作地点
          let placeName = [],
            placeId = [],
            placeType = [];
          workplace.map((i) => {
            placeName.push(i.locationName);
            if (i.location) {
              placeId.push(i.location);
              placeType.push("0");
            } else {
              //临时单位
              placeId.push(i.locationName);
              placeType.push("-1");
            }
          });
          data.locationName = placeName.toString();
          data.locationArr = placeId;
          data.location = placeId.toString();
          data.locationType = placeType.toString();
          let workplaceOption = this.$utils.getOptionData(
            placeName.toString(),
            placeId.toString(),
            placeType.toString()
          );

          if (this.$refs.basicForm) {
            this.$refs.basicForm.setItemOption("deviceName", deviceOption); //设备
            this.$refs.basicForm.setItemOption("deptManageName", option);
            this.$refs.basicForm.setItemOption("locationName", workplaceOption);
          }
          /* 给设备输入框赋值 */
          data.deviceName = deviceName.toString();
          data.deviceId = device.toString();
          data.deviceArr = device;
          /* 给设备管理单位框赋值 */
          data.deptManageArr = deptManage;
          this.formData = data;
        }, 100);
      });
    },
    //获取大修详情overhaulDetails
    getOverhaulDetails() {
      let query = this.$route.query;
      overhaulDetails(query.orderId).then((res) => {
        let data = res.data;
        let {
          deptManage,
          deptManageName,
          major,
          location,
          locationName,
          nature,
          startTime,
          endTime,
          context,
        } = data;
        let form = {
          deptManage,
          deptManageName,
          major,
          location,
          locationName,
          nature: nature ? "1" : "0",
          startTime,
          endTime,
          context,
          sourceId: "enter_order",
        };
        /* 工单标题 */
        this.deptManageName = deptManageName;
        this.currentContext = context;
        this.orderTitle = deptManageName + context;
        this.$emit("initUserInput", false);
        /* 工期 */
        form.timeLimit = this.$utils.getTimeDiffe(
          new Date(startTime),
          new Date(endTime)
        );
        /* 设备管理单位 */
        form.deptManageArr = deptManage;
        this.deptManage = deptManage;
        let option = this.$utils.getOptionData(deptManageName, deptManage, "0");
        this.$refs.basicForm.setItemOption("deptManageName", option);
        form.dispatchTime = [startTime, endTime];
        setTimeout(() => {
          this.formData = form;
        }, 100);
      });
    },
    //保存附件
    saveAttachFile() {
      this.$refs.attachForm.save();
    },
    getTitle() {
      return this.orderTitle;
    },
    //展示检修计划包
    showPlanPackage(row) {
      switch (this.menuType) {
        case "maintain":
          this.goDetailPage(row.planId, "maintenancePlanDetail", "detail");
          break;
        case "repair":
          this.goDetailPage(row.planId, "overhaulPlanPackageDetail", "detail");
          break;
        default:
          this.goDetailPage(row.planId, "experimentPlanDetail", "detail");
          break;
      }
    },
    //跳转到详情页
    goDetailPage(id, router, type) {
      const { href } = this.$router.resolve({
        name: router,
        query: {
          id: id ? id : "",
          pageType: type ? type : "",
        },
      });
      window.open(href, "_blank");
    },
    getFormData(isCheck) {
      return this.$refs.basicForm.getFormData(isCheck);
    },
    //返回设备信息
    getEquipList() {
      return this.orderEquipPoList;
    },
    //返回工作地点
    getLocationList() {
      return this.workplace;
    },
    setAttachId(id, type) {
      new Promise((resolve, reject) => {
        this.attachSetting.businessId = id;
        resolve(this.attachSetting);
      }).then(() => {
        let pageType = type;
        if (["add", "orderAdd"].includes(type)) {
          pageType = "add";
        }
        this.$refs.attachForm.doSubmitFiles(pageType);
      });
    },
    //表单是否显示选设备框
    changeFormItem(value) {
      let itemArr = [];
      //深度拷贝数组对象(可拷贝函数)
      $.extend(true, itemArr, this.basicConfig.itemArr);
      for (let i = 0; i < itemArr.length; i++) {
        if (itemArr[i].prop == "deviceName") {
          if (value == "1") {
            //是
            itemArr[i].isHide = true;
          } else {
            //否
            itemArr[i].isHide = false;
            itemArr[i].managerUnit = [this.deptManage];
          }
          break;
        }
      }
      this.basicConfig.itemArr = itemArr;
    },
  },
};
</script>
<style lang="less" scoped>
.attachConten {
  display: flex;
  flex-flow: wrap nowrap;
  .redPoint {
    color: red;
  }
  .attachTitle {
    width: 120px;
  }
  .tebleDiv {
    width: 100%;
  }
}
.input-link /deep/.el-input__inner {
  cursor: pointer;
  color: royalblue;
}
</style>
